package com.gupaoedu.vip;

import com.gupaoedu.vip.discovery.IServiceDiscovery;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @Author: JLL
 * @Date: 2019/6/18 0:05
 */
public class RemoteInvocationHandler implements InvocationHandler {

    /*private String host;
    private int port;*/
    private IServiceDiscovery serviceDiscovery;
    private String version;

    public RemoteInvocationHandler(IServiceDiscovery serviceDiscovery,String version) {
        this.serviceDiscovery=serviceDiscovery;
        this.version=version;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("调用接口的方法，到invoke方法里");
        RpcRequest rpcRequest = new RpcRequest();
        rpcRequest.setClassName(method.getDeclaringClass().getName());
        rpcRequest.setMethodName(method.getName());
        rpcRequest.setParameters(args);
        /*rpcRequest.setVersion("v1.0");
        rpcRequest.setVersion("v2.0"); //覆盖*/
        rpcRequest.setVersion(version);
        String serviceName=rpcRequest.getClassName();
        if(!StringUtils.isEmpty(version)){
            serviceName=serviceName+"-"+version;
        }
        //远程通信、这里的逻辑封装到了RpcNetTransport类里，单独写在这里也可以

        String serviceAddress=serviceDiscovery.discovery(serviceName);
        RpcNetTransport netTransport=new RpcNetTransport(serviceAddress);
        Object result = netTransport.send(rpcRequest);


        return result;
    }
}
